package com.jiangnan.ui.activity

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.google.zxing.BarcodeFormat
import com.google.zxing.integration.android.IntentIntegrator
import com.jiangnan.R
import com.jiangnan.databinding.ActivityBookMainBinding
import com.jiangnan.ui.adapter.RepositoryQuickAdapter
import com.jiangnan.util.GlideUtil
import com.jiangnan.util.ToastUtil
import com.jiangnan.viewmodel.BookViewModel
import com.jiangnan.viewmodel.ISBNViewModel
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.toRequestBody

class BookMainActivity : BaseActivity(), View.OnClickListener {

    private val TAG = "BookMainActivity"

    private lateinit var binding: ActivityBookMainBinding
    private lateinit var isbnViewModel: ISBNViewModel
    private lateinit var bookViewModel: BookViewModel


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 使用 DataBinding 初始化布局
        binding = DataBindingUtil.setContentView(this, R.layout.activity_book_main)
        // 初始化 ViewModel
        isbnViewModel = ViewModelProvider(this)[ISBNViewModel::class.java]
        bookViewModel = ViewModelProvider(this)[BookViewModel::class.java]
        binding.viewModel = isbnViewModel
        binding.lifecycleOwner = this

        // 测试用的 ISBN
//        isbnViewModel.setScanResult("9787559855022")

        // 设置扫描按钮点击事件
        btnScanQrcode()
        // 监听 toastMessage
        toastMessage()
        // 设置提交事件
        binding.btnBookSubmit.setOnClickListener(this)
        binding.btnUploadImg.setOnClickListener(this)

        uplodeImg()

    }

    /**
     * 两种方式加载图片
     */
    private fun uplodeImg() {
        // 观察 ViewModel 中的 book LiveData，当数据更新时加载图片
        isbnViewModel.book.observe(this) { book ->
            if (book != null && book.img!!.isNotEmpty()) {
                // 将图片加载到 ivBookImg
                GlideUtil.loadImageWithPlaceholder(
                    this,
                    book.img!!,
                    R.drawable.img_default,
                    R.drawable.img_error,
                    binding.ivBookImg
                )
    //                ToastUtil.showShort(this, book.img)
    //                Log.d(TAG, "图书封面路径为1111111111：" + book.img)
            }else{
                binding.ivBookImg.setImageDrawable(null)
            }
        }

        // 观察上传成功后的封面 URL，更新 ImageView（使用 Glide 加载图片）
        isbnViewModel.coverUrl.observe(this) { url ->
            if (!url.isNullOrEmpty()) {
                GlideUtil.loadImageWithPlaceholder(
                    this,
                    url,
                    R.drawable.img_default,
                    R.drawable.img_error,
                    binding.ivBookImg
                )
            }
        }
    }

    private fun btnScanQrcode() {
        binding.ivQrcode.setOnClickListener {
            val integrator = IntentIntegrator(this)
            integrator.setDesiredBarcodeFormats(
                listOf(
                    BarcodeFormat.EAN_13.name, // 常见的图书ISBN格式
                    BarcodeFormat.UPC_A.name,  // 其他一维码格式
                    BarcodeFormat.QR_CODE.name // 二维码格式
                )
            )
            integrator.setPrompt("请扫描图书ISBN")
            integrator.setCameraId(0) // 使用后置摄像头
            integrator.setBeepEnabled(true)
            integrator.setBarcodeImageEnabled(false)
            integrator.initiateScan()
        }
    }

    private fun toastMessage() {
        isbnViewModel.toastMessage.observe(this) { event ->
            event.getContentIfNotHandled()?.let { message ->
                ToastUtil.showShort(this, message)
            }
        }
    }

    // 处理扫描结果
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        if (result != null) {
            if (result.contents == null) {
                // 取消扫描
                isbnViewModel.setScanResult("取消扫描")
            } else {
                // 成功扫描到结果（ISBN）
                isbnViewModel.setScanResult(result.contents)
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.btn_book_submit -> {
                if (isbnViewModel.book.value!!.title == null || isbnViewModel.book.value!!.author!!.isEmpty() || isbnViewModel.book.value!!.isbn!!.isEmpty() || isbnViewModel.book.value!!.price!!.isEmpty()){
                    ToastUtil.showShort(this,"必填信息不可为空")
                }else{
                    isbnViewModel.saveBook(isbnViewModel.book.value!!)
                    isbnViewModel.clear()
                }

//                val adapter = RepositoryQuickAdapter()
//                adapter.notifyDataSetChanged()
            }
            R.id.btn_upload_img ->{
                getImageContent.launch("image/*")
                ToastUtil.showShort(this,"点击了上传按钮")
            }
         }
    }

    // 注册图片选择回调
    private val getImageContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
        uri?.let { selectedUri ->
            // 从内容解析器中读取图片数据
            contentResolver.openInputStream(selectedUri)?.use { inputStream ->
                val bytes = inputStream.readBytes()
                // 构建 RequestBody（图片类型）
                val requestBody = bytes.toRequestBody("image/*".toMediaTypeOrNull())
                // 构造一个文件名，例如：cover_时间戳.jpg
                val fileName = "cover_${System.currentTimeMillis()}.jpg"
                // 构造 MultipartBody.Part 对象，字段名需和后端接收一致，这里假设为 "file"
                val part = MultipartBody.Part.createFormData("file", fileName, requestBody)
                // 调用 ViewModel 上传方法
                isbnViewModel.uploadCoverImage(part)
            }
        }
    }

}